package com.example.qiniuapi.service.impl;

import com.example.qiniuapi.data.QiNiuData;
import com.example.qiniuapi.data.UploadParam;
import com.example.qiniuapi.service.QiNiuApiService;
import com.example.qiniuapi.utils.QiNiuUntil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


@Service
@AllArgsConstructor
@Slf4j
public class IQiNiuApiService implements QiNiuApiService {

    @Override
    public QiNiuData uploadFile(UploadParam uploadParam) {
        Configuration cfg = new Configuration(Region.region1());
        cfg.useHttpsDomains = false;
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;//制定上传版本为V2

        UploadManager uploadManager = new UploadManager(cfg);
        String key = "";
        if (uploadParam.getDirectory() != null && !uploadParam.getDirectory().isEmpty()){
            key = uploadParam.getDirectory() + "/" + uploadParam.getFilename();
        }else {
            key = uploadParam.getFilename();
        }
        Auth auth = Auth.create(QiNiuUntil.ACCESS_KEY, QiNiuUntil.SECRET_KEY);
        String upToken = auth.uploadToken(QiNiuUntil.BUCKET_NAME);
        try {
            Response response = uploadManager.put(uploadParam.getFile(), key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            QiNiuData result = new QiNiuData();
            result.setKey(putRet.key).setHash(putRet.hash).setResponse("OK").setStatus(200);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            return result;
        } catch (QiniuException ex) {
            ex.printStackTrace();
//            log.error("上传文件发生异常", ex);
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    QiNiuData result = new QiNiuData();
                    result.setResponse(body).setStatus(500);
                    System.out.println(body);
                    return result;
                } catch (Exception ignored) {
                }
            }
        }
//        return new QiNiuData().setResponse("未知异常");
        return null;
    }
}
